import pyipmi
import pyipmi.interfaces

class IPMICollector:
    def __init__(self, host):
        self.host = host
        self.interface = pyipmi.interfaces.create_interface('rmcp',
                                                          slave_address=0x81,
                                                          host_target_address=0x20)

    def collect_all(self):
        """收集所有IPMI监控数据"""
        try:
            ipmi = pyipmi.create_connection(interface=self.interface)
            ipmi.session.set_session_type_rmcp(host=self.host.ip_address,
                                             port=623)
            ipmi.session.set_auth_type_user(username=self.host.ipmi_username,
                                          password=self.host.ipmi_password)
            ipmi.target = pyipmi.Target(ipmb_address=0x20)
            ipmi.session.establish()

            try:
                # 收集传感器数据
                self.host.temperature = self._get_temperature(ipmi)
                self.host.power_status = self._get_power_status(ipmi)
                self.host.fan_speed = self._get_fan_speed(ipmi)
                
                self.host.save()
            finally:
                ipmi.session.close()
            
        except Exception as e:
            print(f"IPMI数据收集失败: {str(e)}")
            raise

    def _get_temperature(self, ipmi):
        try:
            # 获取温度传感器数据
            sensors = []
            for s in ipmi.device_get_sensor_reading():
                if s.sensor_type == pyipmi.sensor.SENSOR_TYPE_TEMPERATURE:
                    sensors.append(s.raw)
            if sensors:
                return sum(sensors) / len(sensors)  # 返回平均温度
        except Exception as e:
            print(f"获取温度数据失败: {str(e)}")
        return None

    def _get_power_status(self, ipmi):
        try:
            status = ipmi.get_chassis_status()
            return status.power_on
        except Exception as e:
            print(f"获取电源状态失败: {str(e)}")
        return None

    def _get_fan_speed(self, ipmi):
        try:
            sensors = []
            for s in ipmi.device_get_sensor_reading():
                if s.sensor_type == pyipmi.sensor.SENSOR_TYPE_FAN:
                    sensors.append(s.raw)
            if sensors:
                return sum(sensors) / len(sensors)  # 返回平均风扇速度
        except Exception as e:
            print(f"获取风扇速度失败: {str(e)}")
        return None 